/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.ui;

import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

import org.jdesktop.swingx.JXTitledPanel;
import org.poxd.model.Snippet;
import org.poxd.syntax.JEditTextArea;
import org.poxd.syntax.JavaTokenMarker;

/**
 * @author pollux
 * 
 */
public class CodePanel extends JXTitledPanel {
	private static final long serialVersionUID = 1L;
	private JPanel content;
	private JPanel top;
	private JEditTextArea codeArea;
	private JSplitPane split;
	private Snippet currentSnippet;
	private JTextArea descArea;

	public CodePanel() {
		setTitle("Snippet");
		content = new JPanel();
		content.setLayout(new GridLayout(1, 1));
		initDescPanel();
		initCodePanel();

		split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, top, codeArea);
		split.setOneTouchExpandable(true);
		split.setResizeWeight(0.5);
		content.add(split);

		setContentContainer(content);
	}

	private void initCodePanel() {
		codeArea = new SniweTextArea();
		codeArea.setEditable(false);
		codeArea.setCaretVisible(false);
		codeArea.setCaretBlinkEnabled(false);
		codeArea.getPainter().setInvalidLinesPainted(false);
		codeArea.setTokenMarker(new JavaTokenMarker());
		codeArea.setMaximumSize(new Dimension(Integer.MAX_VALUE,
				Integer.MAX_VALUE));
	}

	private void initDescPanel() {
		top = new JPanel(new GridLayout(1,1));
		descArea = new JTextArea();
		descArea.setLineWrap(true);
		descArea.setWrapStyleWord(true);
		JScrollPane scrollPane = new JScrollPane(descArea);
		top.add(scrollPane);
	}

	public void setSnippet(Snippet s) {
		currentSnippet = s;
		if (currentSnippet == null) {
			codeArea.setText("");
			descArea.setText("");
			setTitle("Snippet");
		} else {
			codeArea.setText(s.getCode() == null ? "" : s.getCode());
			descArea.setText(s.getDescription() == null ? "" : s.getDescription());
			setTitle(s.getTitle());
		}
		codeArea.setCaretPosition(0);
		repaint();
	}
}
